<template>
    <div class="substance_edit-help">
        <div class="ls-card">
            <el-page-header :content="mode == 'add' ? '批量添加短剧集' : ''" @back="$router.go(-1)" />
        </div>

        <div class="ls-card m-t-16 form-container">
            <div class="form-left">
                <el-form :rules="rules" ref="form" :model="form" label-width="120px" size="small">
                    <!-- 标题输入框 -->
                    <el-form-item label="短剧ID" prop="title">
                        <el-input class="ls-input" v-model="form.video_id" show-word-limit disabled>
                        </el-input>
                    </el-form-item>
                    <!-- <el-form-item label="短剧封面" prop="image">
                        <material-select :limit="1" v-model="form.image" />
                        <div class="muted xs">建议尺寸：240*180像素</div>
                    </el-form-item> -->
                    <el-form-item label="单集价格" prop="synopsis">
                        <el-input class="ls-input" v-model="form.price" placeholder="单集价格"></el-input>
                    </el-form-item>
                    <el-form-item label="单集VIP价格" prop="synopsis">
                        <el-input class="ls-input" v-model="form.vip_price" placeholder="单集VIP价格"></el-input>
                    </el-form-item>
                    <el-form-item label="免费集数" prop="sort">
                        <el-input type="number" class="ls-input" v-model.number="form.free"
                            placeholder="请输入免费集数"></el-input>
                    </el-form-item>
                    <!-- 帮助状态 -->
                    <el-form-item label="选择视频" prop="is_show">
                        <input type="file" multiple accept="video/*" @change="videoSelect" />
                    </el-form-item>
                    <el-form-item label="操作">
                        <el-button size="small" type="primary" @click="uploadQiniu">上传</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="form-right">
                <el-table ref="paneTable" border :data="videoFiles" style="width: 100%" height="400" size="mini">
                    <el-table-column label="剧集标题" min-width="150">
                        <template slot-scope="scope">
                            <span style="margin-left: 10px">
                                <el-input class="ls-input" v-model="scope.row.title" show-word-limit>
                                </el-input>
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="每集价格" min-width="180">
                        <template slot-scope="scope">
                            <span style="margin-left: 10px">
                                <el-input class="ls-input" v-model="scope.row.price" show-word-limit>
                                </el-input>
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="每集VIP价格" min-width="180">
                        <template slot-scope="scope">
                            <span style="margin-left: 10px">
                                <el-input class="ls-input" v-model="scope.row.vip_price" show-word-limit>
                                </el-input>
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="顺序" min-width="150">
                        <template slot-scope="scope">
                            <span style="margin-left: 10px">
                                <el-input class="ls-input" v-model="scope.row.sort" show-word-limit>
                                </el-input>
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="上传进度" min-width="150">
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <!-- 底部保存或取消 -->
        <div class="bg-white ls-fixed-footer">
            <div class="row-center flex" style="height: 100%">
                <el-button size="small" @click="$router.go(-1)">取消</el-button>
                <el-button size="small" type="primary" @click="onSubmit('form')">保存</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Vue,Prop } from 'vue-property-decorator'
import { getQiniuToken ,videoBatchAdd} from '@/api/visionapi/index'
import MaterialSelect from '@/components/material-select/index.vue'
import LsEditor from '@/components/editor.vue'
import { PageMode } from '@/utils/type'
var qiniu = require('qiniu-js')
@Component({
    components: {
        LsEditor,
        MaterialSelect
    }
})
export default class ArticleEdit extends Vue {
    @Prop({default: ''}) id!: String
    /** S Data **/
    mode: string = PageMode.ADD // 当前页面: add-添加角色 edit-编辑角色
    qiniuToken: string = ""
    // 表单数据
    form: any = {
        video_id: this.id, // 当前编辑用户的身份ID
        title: '', // 标题
        // image: '', // 封面图片
        free: 0, // 免费数量
        vip_price:0,
        price: 0, // 每集价格
        video_item: []
    }
    videoFiles: Array<object> = []
    // 表单校验
    rules: object = {
    }

    /** E Data **/

    /** S Methods **/
    // 提交表单
    onSubmit(formName: string) {
        const refs = this.$refs[formName] as HTMLFormElement
        refs.validate((valid: boolean): void => {
            if (!valid) {
                return
            }

            // 请求发送
            switch (this.mode) {
                case PageMode.ADD:
                    return this.handleArticleAdd()
            }
        })
    }

    // 添加帮助文章
    handleArticleAdd() {
        this.form.video_item = this.videoFiles;
        videoBatchAdd(this.form).then(() => {
            setTimeout(() => this.$router.go(-1), 500)
        })
    }

    videoSelect(e: any) {
        let files = e.target.files;
        let videoFiles = [];
        for (var i = 0; i < files.length; i++) {
            var name = this.removeSuffix(files[i].name, '.mp4')
            if (!parseInt(name)) {
                this.$message.error('每集命名必须为1、2、3这种数字')
            }
            name = this.convertToChinese(parseInt(name));
            name = "第" + name + "集";
            var price = this.form.free < i + 1 ? this.form.price : 0;
            var vip_price = this.form.free < i + 1 ? this.form.vip_price : 0;
            videoFiles[i] = {
                title: name,
                price: price,
                vip_price: vip_price,
                sort: i,
                video_path: '',
                status: "等待上传",
                file: files[i]
            };
        }
        this.videoFiles = videoFiles;
    }


    removeSuffix(str: string, suffix: string) {
        if (str.endsWith(suffix)) {
            return str.slice(0, -suffix.length);
        }
        return str;
    }


    convertToChinese(num: Number) {
        const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
        const units = ['', '十', '百', '千', '万'];
        let str = num.toString();
        let chineseStr = '';

        for (let i = 0; i < str.length; i++) {
            const numChar = parseInt(str[i]);
            const unitChar = units[str.length - 1 - i] || '';
            chineseStr += (numChar === 0 ? '' : chineseNumbers[numChar] + unitChar);
        }
        return chineseStr.replace(/^一十/, '十');
    }
    uploadQiniu() {
        console.log(this.videoFiles);
        for (var i = 0; i < this.videoFiles.length; i++) {
            this.uploadWithSDK(i, this.videoFiles[i]);
        }
    }

    uploadWithSDK(number: Number, file: any) {
        var config = { useCdnDomain: true };
        var putExtra: any = {
            customVars: {}
        };
        // eslint-disable-next-line
        var finishedAttr: any = [];
        // eslint-disable-next-line
        var compareChunks: any = [];
        var observable;
        var key = file.file.name;
        var temp = key.split('.');
        var fileName2 = this.getTimeId(8, 12)
        var pathname = "video/" + this.createPic() + fileName2;//七牛云的路径  如果在目录路径是：根目录/pageck/test 那么这个值就是：page/test
        key = pathname + '.' + temp[temp.length - 1];//详细的文件名称（包含路径）page/test/test.zip  就会自动上传到相对应的文件夹

        var board: any = {};
        putExtra.customVars["x:name"] = key.split(".")[0];
        board.start = true;
        file.status = "进度：准备上传中";
        var str = Date.now()
        var error = function (err: any) {
            board.start = true;
            // $(".control-upload").text("继续上传");
            console.log(err);
            alert("上传出错")
        };
        var complete = function (res: any) {
            console.log(res);
            file.video_path = res.key
        };

        var next = function (response: any) {
            var chunks = response.chunks || [];
            var total = response.total;//上传总进度 因为如果文件过大 接口会自动分段上传
            // 这里对每个chunk更新进度，并记录已经更新好的避免重复更新，同时对未开始更新的跳过
            for (var i = 0; i < chunks.length; i++) {
                if (chunks[i].percent === 0 || finishedAttr[i]) {
                    continue;
                }
                if (compareChunks[i].percent === chunks[i].percent) {
                    continue;
                }
                if (chunks[i].percent === 100) {
                    finishedAttr[i] = true;
                }
            }
            file.status = "进度：" + parseInt(total.percent) + "%";
            compareChunks = chunks;
        };

        var subObject = {
            next: next,
            error: error,
            complete: complete
        };
        var subscription;
        // 调用sdk上传接口获得相应的observable，控制上传和暂停
        board.start = false;
        // 重要的调用接口
        observable = qiniu.upload(file.file, key, this.qiniuToken, putExtra, config);
        // 上传的接口 暂停的接口为observable.unsubscribe(subObject);
        subscription = observable.subscribe(subObject);
    }

    getTimeId(len: Number, radix: Number) {
        if (len) {
            const time = new Date().getTime()
            const uuid = this.getuuid(len, radix)
            return `${time}${uuid}`
        } else {
            console.log('请输入长度')
        }
    }
    createPic() {
        var now = new Date();
        var year = now.getFullYear(); //得到年份
        var month = now.getMonth();//得到月份
        var date = now.getDate();//得到日期
        month = month + 1;
        if (month < 10) month = 0 + month;
        if (date < 10) date = 0 + date;
        var number = now.getSeconds() % 43; //这将产生一个基于目前时间的0到42的整数。
        var time = year + '/' + month + '/' + date + '/';
        return time + "_" + number;
    }
    getuuid(len: any, radix: any) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
        var uuid = []
        var i = 0
        radix = radix || chars.length

        if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
        } else {
            var r
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
            uuid[14] = '4'

            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16
                    uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
                }
            }
        }

        return uuid.join('')
    }
    /** E Methods **/

    /** S Life Cycle **/
    created() {
        const query: any = this.$route.query
        if (query.mode) {
            this.mode = query.mode
        }
        getQiniuToken({}).then(res => {
            this.qiniuToken = res.token;
        })
    }

    /** E Life Cycle **/
}
</script>

<style lang="scss" scoped>
.form-container {
    display: flex;

    .form-left {
        width: 500px;
    }

    .form-right {
        width: 800px;
    }
}
</style>
